/**
 * 
 */
package com.ywm8.ywm.admin.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ywm8.ywm.admin.dao.BaseDao;

/**
 * @author wangruishun
 * @version ywm8 1.0 2014-1-8 上午11:37:26
 */
@SuppressWarnings("rawtypes")
public class BaseDaoImpl<T> implements BaseDao<T> {

	private Class clazz;

	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	@Resource
	private SessionFactory sf;

	public void saveEntity(T t) {
		sf.getCurrentSession().save(t);
	}

	public void updateEntity(T t) {
		sf.getCurrentSession().update(t);
	}

	public void deleteEntity(T t) {
		sf.getCurrentSession().delete(t);
	}


	
	public void saveOrUpdateEntity(T t) {
		sf.getCurrentSession().saveOrUpdate(t);
	}

	public void batchEntityByHQL(String hql, Object... objects) {
		Session s = sf.getCurrentSession();
		Query q = s.createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		q.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public T getEntity(Integer id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public T loadEntity(Integer id) {
		return (T) sf.getCurrentSession().load(clazz, id);

	}

	@SuppressWarnings("unchecked")
	public List<T> findEntityByHQL(String hql, Object... objects) {
		Session s = sf.getCurrentSession();
		Query q = s.createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		return q.list();
	}

}
